//Key Class Code
////Graham Foster
////Content for key class for cipher solver

#include <iostream>
#include <string>
#include "key.h"

using namespace std;

Key::Key()
{
	for (int i=0; i<26; i++)
	{
		list[i]=i+65; //taking advantage of sequential ASCII values
		mean[i]='_';
	}
	length=26;
}

void Key::printKey()
{
	printf("The key is (original above, translation below):\n");
	printf("*"); //strings enclosed in "*" to highlight line ends, spaces, etc
	
	printf("%s",list);
	printf("*\n*");

	printf("%s",mean);
	printf("*\n\n");
}

int Key::saveKey(char fileName[])
{
	FILE *fout;
	//fin.open(fileName);
	if ((fout = fopen(fileName, "w"))==NULL)
	{
		return 1;
	}
	//print length of the key
	fprintf(fout,"%d\n",length);
	if (length > maxKeySize)
	{
		printf ("Emergency!! unhandled length of key");
	}
	//print the key items
	for (int i=0; i<length; i++)
	{
		fprintf(fout,"%c",list[i]);
	}
	fprintf(fout,"\n\n");
	//print the key translations
	for (int i=0; i<length; i++)
	{
		fprintf(fout,"%c",mean[i]);
	}
	fprintf(fout,"\n\n");
	fclose(fout);
}

int Key::loadKey(char fileName[])
//returns 1 on failure
{
	FILE *fin;
	//fin.open(fileName);
	if ((fin = fopen(fileName, "r"))==NULL)
	{
		return 1;
	}
	//retrieve the length of the key
	fscanf(fin,"%d",&length);
	if (length > maxKeySize)
	{
		printf ("Emergency!! unhandled length of key");
		return 1;
	}
	getc(fin); //skimming extra characters
	//get the key items
	for (int i=0; i<length; i++)
	{
		fscanf(fin,"%c",&list[i]);
	}
	list[length]='\0'; //otherwise string not terminated properly
	getc(fin);
	getc(fin);
	//get the key translations
	for (int i=0; i<length; i++)
	{
		fscanf(fin,"%c",&mean[i]);
	}
	mean[maxKeySize-1]='\0';
	fclose(fin);
}

int Key::subChar(char char1, char char2)
//returns 0 on success, 1 on failure
{
	bool found; //if char1 was found in the spanning set

	for (int i=0; i<length; i++)
	{
		if (list[i] == char1)
		{
			mean[i] = char2;
			found=true;
		}
	}
	if (found == false)
	{
		cout << "Warning, the character to be substituted for was not found" << endl;
		return 1;
	}
	return 0;
}

char Key::lookupChar(char first)
{
	bool found=false;
	for (int j=0; j<length; j++)
	{
		if (list[j]==first)
		{
			found=true;
			return mean[j];
		}
	}
	if (found==false)
	{
		return first;
	}
}
